import { Button, Radio, Form, Input, DatePicker, Upload, message } from 'antd';
import { useSelector } from "react-redux"
import { useEffect, useState } from "react"
import { BilibiliFilled, LoadingOutlined, PlusOutlined } from "@ant-design/icons"
import 'dayjs/locale/zh-cn';
import styles from "./index.module.scss"
import dayjs from 'dayjs';
import type { GetProp, UploadProps } from 'antd';
import { User_up_avatar } from "@/apis/user"
import { Local } from "@/utils/local"
import { axios_user_upload } from "@/store/Userstore/UserStore"
import { useDispatch } from "react-redux"
import type { AppDispatch } from "@/store"
import Guard from "@/guard"
const base_url = import.meta.env.VITE_APP_URL
const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
};
const normFile = (e: any) => {
    if (Array.isArray(e)) {
        return e;
    }
    return e?.fileList;
};
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/webp';
    if (!isJpgOrPng) {
        message.error('只能上传jpg,png,gif,webp');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('最大2MB!');
    }
    return isJpgOrPng && isLt2M;
};

function getZodiacSign(dateString: string) {
    if (!dateString) return ""
    const date = new Date(dateString);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const zodiacSigns = [
        { sign: "摩羯座", startDate: "01-01", endDate: "01-19" },
        { sign: "水瓶座", startDate: "01-20", endDate: "02-18" },
        { sign: "双鱼座", startDate: "02-19", endDate: "03-20" },
        { sign: "白羊座", startDate: "03-21", endDate: "04-19" },
        { sign: "金牛座", startDate: "04-20", endDate: "05-20" },
        { sign: "双子座", startDate: "05-21", endDate: "06-21" },
        { sign: "巨蟹座", startDate: "06-22", endDate: "07-22" },
        { sign: "狮子座", startDate: "07-23", endDate: "08-22" },
        { sign: "处女座", startDate: "08-23", endDate: "09-22" },
        { sign: "天秤座", startDate: "09-23", endDate: "10-23" },
        { sign: "天蝎座", startDate: "10-24", endDate: "11-22" },
        { sign: "射手座", startDate: "11-23", endDate: "12-21" },
        { sign: "摩羯座", startDate: "12-22", endDate: "12-31" }
    ];

    const monthDay = (`0${month}`).slice(-2) + "-" + (`0${day}`).slice(-2);

    for (const zodiac of zodiacSigns) {
        if ((monthDay >= zodiac.startDate && monthDay <= zodiac.endDate) ||
            (zodiac.sign === "摩羯座" && monthDay <= zodiac.endDate)) {
            return zodiac.sign;
        }
    }

    return monthDay;
}
const UserEdit = () => {
    useEffect(() => {
        form.setFieldsValue({
            username: userinfo.username,
            description: userinfo.description,
            bilibili: userinfo.bilibili,
            // avatar: userinfo.avatar,
            sex: userinfo.sex
        })
        settempurl(userinfo.avatar)
        setImageUrl(base_url + userinfo.avatar)
        // console.log(userinfo)
    }, [])
    const dispatch = useDispatch<AppDispatch>()
    const [form] = Form.useForm();
    const thems = useSelector((state: any) => state.Appstore.theme)

    const userinfo = useSelector((state: any) => state.UserStore.userinfo)
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const [tempurl, settempurl] = useState<string>('')
    const onFinish = async (values: any) => {
        const value = {
            ...values,
            brithday: dayjs(values.brithday).format('YYYY-MM-DD'),
            avatar: tempurl,
            _id: Local.get_info()._id
        }
        await dispatch(axios_user_upload(value))
        form.resetFields();
        setImageUrl('')
        settempurl('')
        console.log('Success:', value);
    }
    const onChange = (_: any, date: any) => {

        form.setFieldsValue({
            constellation: getZodiacSign(date)
        })
    }
    const InputChange = (e: any) => {
        console.log(e.target.value)
        if (e.target.value.length > 40) {
            form.setFieldsValue({ description: e.target.value.slice(0, 40) })
        }
    }

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>{loading ? '上传中' : '上传'}</div>
        </button>
    );
    const myup = async (e: any) => {
        setLoading(true)
        const formData = new FormData();
        formData.append('file', e.file)
        const res: any = await User_up_avatar(formData)
        if (res.code === 200) {
            settempurl(res.path)
            setLoading(false)
            setImageUrl(base_url + res.path)
        }
    }
    return (
        <Guard>

            <div style={{ display: "flex", justifyContent: "center", width: "100%", }}>
                <div style={{ width: "50%", height: '90vh', overflowY: "scroll", overflowX: "hidden", background: thems ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.4)', marginTop: "10px", padding: "10px" }}>
                    <div style={{ textAlign: "center", margin: '10px 0' }}>修改资料</div>
                    <Form
                        form={form}
                        name="basic"

                        style={{ maxWidth: 600, }}
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 10 }}
                            label="用户名"
                            name="username"
                            rules={[{ required: true, message: '长度在2-7', max: 7, min: 2 }]}
                        >
                            <Input placeholder='用户名' />
                        </Form.Item>
                        <Form.Item
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 16 }}
                            label="出生日期"
                            name="brithday"

                            rules={[{ required: true, message: "必填" }]}
                        >
                            <DatePicker onChange={onChange} />
                        </Form.Item>
                        <Form.Item
                            label="星座"
                            name="constellation"
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 5 }}
                            rules={[{ required: true, message: "必填" }]}

                        >
                            <Input disabled={true} />
                        </Form.Item>
                        <Form.Item
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 16 }}
                            label="性别"
                            name="sex"
                            initialValue={"male"}
                            rules={[{ required: true, message: "必填" }]}
                        >
                            <Radio.Group name="sex" >
                                <Radio value="male">男</Radio>
                                <Radio value="female">女</Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item
                            label="描述"
                            name="description"
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 10 }}


                        >
                            <Input.TextArea onChange={InputChange} autoSize={{ minRows: 1, maxRows: 3 }} count={

                                {
                                    max: 40,
                                    strategy: () => 1,

                                    show: ((args: { value: string; count: number; maxLength?: number }) => {

                                        return <p>{args.value.length}/{args.maxLength}</p>
                                    }),
                                }
                            } />
                        </Form.Item>
                        <Form.Item
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 10 }}
                            label="bilibili链接"
                            name="bilibili"
                        >
                            <Input prefix={<BilibiliFilled style={{ color: "deeppink" }} />}  ></Input>
                        </Form.Item>
                        <Form.Item
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 5 }}
                            label="头像"
                            valuePropName="fileList"
                            name="avatar"
                            getValueFromEvent={normFile}
                        >

                            <Upload
                                name="file"
                                listType="picture-circle"
                                className={styles.uploader}
                                showUploadList={false}
                                customRequest={myup}
                                beforeUpload={beforeUpload}

                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                修改
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </Guard>

    );
}

export default UserEdit;